// pages/pay/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart:null,
    discount:0,
    countPrice:0,
    countNum:0,
    notes:"",
    coupons:[],
    couChang:true,
    usecoupon:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let cart =[]
    let coupons =wx.getStorageSync('coupons')||[]//获取用户优惠券
    coupons = coupons.filter(v=>{//获取未使用优惠券
      return v.state==="unused"
    })
    if(options.products){//从立即购买那跳转则按传过来的参数赋值
    var products = JSON.parse(options.products)
     cart.push(products)
    }else{//从加载到购物车数据选中状态参数赋值
      let oldcart = wx.getStorageSync('cart')||[]
      cart = oldcart.filter(v=>v.checked)
    }
    this.cal(cart)
     this.setData({cart,coupons})
    this.screen(this.data.coupons)
  },
  handle(e){//切换需要使用的优惠券状态，并更改对应的值
    let coupons = this.data.coupons
    coupons.forEach(v=>{v.checked = false})//先把所有优惠券选中状态设置为false
    let usecoupon =  e.currentTarget.dataset.usecoupon||{}//获取点击对应的优惠券
    let index = coupons.findIndex(v=>v.cid===usecoupon.cid)//
    let discount = e.currentTarget.dataset.discount//无优惠时使用
    if(index!==-1){
    coupons[index].checked = true
  }
    this.setData({
      discount:discount,
      coupons:coupons,
      usecoupon:usecoupon
    })
    this.cal(this.data.cart)
    
  },
  handleChang(){
    this.setData({couChang:!this.data.couChang})
  },
  Remarks(e){
    this.setData({notes:e.detail.value})
  },
  screen(coupons){//获取当前订单可使用最优的优惠券
    let countPrice = this.data.countPrice//获取筛选的优惠券数据
    let index = 0;
    let discount = 0;
    let usecoupon ={}
    coupons = coupons.filter(v=>countPrice>=v.condition)//当前优惠券价格
    coupons =  coupons.map((v,i)=>{
      if(v.discount>discount){ 
        discount = v.discount
        usecoupon = v
        v.checked = true
        if(i>0){
        coupons[index].checked  = false
        index = i
      }
      }
      return v
    })
    console.log(coupons);
    this.setData({coupons,discount,usecoupon})
    this.cal(this.data.cart)
  },
  Buy(){
    var that = this
    wx.showModal({
      title:"提示",
      content:'是否确认购买？',
      success (res) {
        if (res.confirm) {
          let orders = wx.getStorageSync('orders')||[];//获取本地的订单信息
          let coupons  = wx.getStorageSync("coupons")//获取本地优惠券信息
          let  ordernum=Date.now().toString()+parseInt(Math.random()*10+1).toString()//随机生成订单号
          var data ={//创建新的订单对象
            num:ordernum,//订单号
            products:that.data.cart,//订单商品
            countprice:(parseFloat(that.data.countPrice)+that.data.discount-0).toFixed(2),//订单实付款价格
            createdate:app.newDate(),//订单创建日期
            state:"unused",//订单使用状态
            price:that.data.countPrice,//订单总价
            discount:that.data.discount.toFixed(2),//订单优惠价格
            Notes:that.data.notes,//订单备注
            finishtime:""//订单使用时间
          }
          orders.unshift(data)//创建好的新订单加到全部订单最前面
          wx.setStorageSync('orders', orders)//存回数据库
          app.userinfo.num+=1//用户购买次数＋1
          app.userinfo.monetary+=parseFloat(that.data.countPrice-0)//用户购买金额自增订单金额

          let index = coupons.findIndex(v=>{
            return v.cid===that.data.usecoupon.cid
          })//获取当前使用优惠券对应总优惠券的下标
          console.log(index)
          if(index!==-1){//如果有使用优惠券，则让对应优惠券的状态为已使用
          coupons[index].state = "used"
          wx.setStorageSync("coupons",coupons)
        }
          let value = {
            orders:orders,
            num:app.userinfo.num,
            monetary:app.userinfo.monetary,
            coupons:coupons
          }
          app.DelShoppingCar()//s删除本地购物车对应的商品信息，并更新用户购物车数据
          app.Update("users","_openid",app.globalData.openid,value)
         wx.redirectTo({
            url: '/pages/orderinfo/index?ordernum='+ordernum,
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '用户点击取消',
            icon:"none"
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  cal(cart){
    let countNum = 0;
    let countPrice = 0;
    cart.forEach(v=>{
        countNum +=v.num;
        countPrice += v.num * v.discount
    })
    countPrice =(countPrice-this.data.discount).toFixed(2)
    this.setData({
      countNum,
      countPrice
    }) 
  }
})